package com.lcf.app.rabbitmq.provider.controller;

import com.lcf.common.model.MqConstant;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author ChenFei
 * @date 2021/12/1
 */
@RestController
@RequestMapping("")
public class SendController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * Spring默认创建的交换机，它会将消息路由至名称与RoutingKey相同的队列。
     *
     * @return
     */
    @GetMapping("send")
    public String send() {
        rabbitTemplate.convertAndSend(MqConstant.DEFAULT_QUEUE, "第一条消息。。。");
        return "success";
    }

    /**
     * 扇形交换机
     * 就是把交换机（Exchange）里的消息发送给所有绑定该交换机的队列，忽略routingKey
     *
     * @return
     */
    @GetMapping("fanout")
    public String fanout() {
        //两个队列都会收到消息
        //rabbitTemplate.convertAndSend(MqConstant.FANOUT_EXCHANGE,MqConstant.FANOUT_QUEUE_ONE, "fanout消息。。。");
        //两个队列都会收到消息
        //rabbitTemplate.convertAndSend(MqConstant.FANOUT_EXCHANGE,MqConstant.FANOUT_QUEUE_TWO, "fanout消息。。。");
        //两个队列都会收到消息
        rabbitTemplate.convertAndSend(MqConstant.FANOUT_EXCHANGE, null, "fanout消息。。。");
        return "success";
    }

    /**
     * 通过RoutingKey路由到与binding key相同的队列。
     *
     * @return
     */
    @GetMapping("direct")
    public String direct() {
        //队列 ‘MqConstant.DIRECT_QUEUE_ONE’ 会收到消息
        //rabbitTemplate.convertAndSend(MqConstant.DIRECT_EXCHANGE, MqConstant.DIRECT_KEY_ONE, "direct消息。。。");
        //队列 ‘MqConstant.DIRECT_QUEUE_TWO’ 会收到消息
        rabbitTemplate.convertAndSend(MqConstant.DIRECT_EXCHANGE, MqConstant.DIRECT_KEY_TWO, "direct消息。。。");
        //不会收到消息
        //rabbitTemplate.convertAndSend(MqConstant.DIRECT_EXCHANGE, null, "direct消息。。。");
        return "success";
    }

    /**
     * 支持通配符级别的binding key，支持一对多的消息发布
     *
     * @return
     */
    @GetMapping("topic")
    public String topic() {
        //队列收到消息
        //rabbitTemplate.convertAndSend(MqConstant.TOPIC_EXCHANGE, "cat.black", "topic消息。。。");
        //不能收到消息
        //rabbitTemplate.convertAndSend(MqConstant.TOPIC_EXCHANGE, "dog.big.white", "topic消息。。。");
        //队列收到消息
        rabbitTemplate.convertAndSend(MqConstant.TOPIC_EXCHANGE, "dog.big", "topic消息。。。");
        return "success";
    }

}
